//
// Created by v on 19-6-25.
//

#include "CMDatabaseProxy.h"

CMDatabaseProxy::CMDatabaseProxy(const char *sqltype, const char *dbfile)
{
    m_dbfile = dbfile;
    m_opened = false;
    if (sqltype == std::string("sqlite"))
    {
        m_dbHandler = new CMDatabaseSqlite(dbfile);
    }
    if (m_dbHandler)
    {
        int ret = m_dbHandler->dbConnect();
        if (ret >= 0)
        {
            m_opened = true;
        }
    }
}

CMDatabaseProxy::~CMDatabaseProxy()
{
    if (m_dbHandler)
    {
        m_dbHandler->dbDisconnect();
    }
    m_opened = false;
}

int CMDatabaseProxy::query(const char *sql, CMDatabaseResult &result)
{
    if (m_dbHandler && m_opened)
    {
        return m_dbHandler->dbQuery(sql, result);
    }
    return -1;
}

int CMDatabaseProxy::queryResult(const char *sql, CMDatabaseResult &result)
{
    if (m_dbHandler && m_opened)
    {
        return m_dbHandler->dbQueryResult(sql, result);
    }
    return 0;
}

void CMDatabaseProxy::debugPrintResult(const CMDatabaseResult &result)
{
    if (result.m_errMsg.length() > 0)
    {
        printf("%s\n", result.m_errMsg.c_str());
        return;
    }
    printf("with result count %lu\n\n", result.m_result.size());
    int index = 0;
    for (auto i : result.m_head)
    {
        if (index++ > 15)
            break;
        printf("%15s", i.c_str());
    }
    printf("\n");
    index = 0;
    for (auto i : result.m_result)
    {
        if (index > 50)
            break;
        printf("\n%d - ", index);
        int maxindex = 0;
        for (auto j : i)
        {
            if (maxindex++ > 15)
                break;
            printf("%15s ", j.c_str());
        }
        index++;
        printf("\n\n");
    }

    printf("==================== next use map to print out "
           "===============================\n\n");
    index = 0;
    for (auto i : result.m_resultEx)
    {
        if (index > 50)
            break;
        std::map<std::string, std::string> out = i;
        printf("%d -> ", index++);
        for (auto k : out)
        {
            printf("%s = [%15s] , ", k.first.c_str(), k.second.c_str());
        }
        printf("\n");
    }
}
